<?php
class Rnaasv_ObjectParser {
	private $instance;

	private function __construct() {

	}

	/**
	 * Devuelve instancia de esta clase
	 *
	 * @return Rnaasv_ObjectParser
	 */
	public static function getInstance() {
		if (!$instance) {
			$instance = new Rnaasv_ObjectParser();
		}
		return $instance;
	}

	/**
	 * Copia los valores de un array a un objeto
	 *
	 * @param array $arr
	 * @param  $object
	 */
	public function array2object(array &$arr,  &$object) {
		foreach($arr as $key => $value) {
			if (property_exists($object, "$key")) {
				//echo "tiene prop: $key\n";
				$object->{$key} = $value;
			} else {
				//echo "no tiene prop: $key\n";
			}
		}
	}

	/**
	 * Copia los valores entre objetos, entre aquellas propiedades que ambos compartan
	 *
	 * @param  $obj1
	 * @param  $obj2
	 */
	public function object2object($obj1,  $obj2) {
		foreach($obj1 as $key => $value) {
			if (property_exists($obj2, "$key")) {
				//echo "tiene prop: $key\n";
				$obj2->{$key} = $value;
			} else {
				//echo "no tiene prop: $key\n";
			}
		}
		return $obj2;
	}

	/**
	 * Copia valores del objeto al array
	 *
	 * @param  $obj1
	 * @param array $arr
	 */
	public function object2array( &$obj1, array &$arr) {
		foreach($obj1 as $key => $value) {
			$arr[$key] = $value;
		}
	}
	
	/**
	 * Convierte el json a objeto
	 * @param string $jsonText
	 * @param  $obj2
	 */
	public function json2object($jsonText,  $obj2) {
		$obj1 = Zend_Json::decode($jsonText, Zend_Json::TYPE_OBJECT);
		return $this->jsonArray2ObjectArray($obj1, $obj2);
	}

	public function jsonArray2MenuResourceArray($jsonText) {
		$jsonArray = Zend_Json::decode($jsonText, Zend_Json::TYPE_OBJECT);
		$salida = $this->array2MenuResourceArray($jsonArray);
		//var_dump($jsonText);
		//var_dump($jsonArray);
		//var_dump($salida);
		//die();
		return $salida;
	}

	public function array2MenuResourceArray($jsonArray) {
		$objSalida = array();
		if (is_array($jsonArray)) {
			for ($i = 0; $i < sizeof($jsonArray); $i++){
				$obj2 = new Rnaasv_MenuResource();
				$newObj = $this->object2object($jsonArray[$i], $obj2);
				//print_r($newObj);
				$newObj->sub = $this->array2MenuResourceArray($newObj->sub);
				$objSalida[] = $newObj;
			}
		}
		return $objSalida;
	}
	
}
?>